package com.ssm.auth.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.ssm.auth.common.enums.IsDeletedFlagEnum;
import com.ssm.auth.domain.bo.AuthRolePermissionBO;
import com.ssm.auth.domain.service.AuhtRolePermissionDomainService;
import com.ssm.auth.infra.basic.entity.AuthRolePermission;
import com.ssm.auth.infra.basic.service.AuthRolePermissionService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Log4j2
public class AuhtRolePermissionDomainServiceImpl implements AuhtRolePermissionDomainService {

    @Resource
    private AuthRolePermissionService authRolePermissionService;

    /**
     * 新增角色权限
     * @param authRolePermissionBO
     * @return
     */
    @Override
    public Boolean add(AuthRolePermissionBO authRolePermissionBO) {
        if(log.isInfoEnabled()) {
            log.info("RolePermissionController.add.bo:{}", JSON.toJSONString(authRolePermissionBO));
        }
        //与数据库交互多次，数据库建立连接耗时，性能差，优化为与数据库交互一次，批量插入
//        Long roleId = authRolePermissionBO.getRoleId();
//        authRolePermissionBO.getPermissionIdList().forEach(permissionId -> {
//            AuthRolePermission authRolePermission = new AuthRolePermission();
//            authRolePermission.setRoleId(roleId);
//            authRolePermission.setPermissionId(permissionId);
//            authRolePermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
//            authRolePermissionService.insert(authRolePermission);
//        });
        List<AuthRolePermission> authRolePermissions = new ArrayList<>();
        Long roleId = authRolePermissionBO.getRoleId();
        authRolePermissionBO.getPermissionIdList().forEach(permissionId -> {
            AuthRolePermission authRolePermission = new AuthRolePermission();
            authRolePermission.setRoleId(roleId);
            authRolePermission.setPermissionId(permissionId);
            authRolePermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            authRolePermissions.add(authRolePermission);
        });
        int count = authRolePermissionService.insertBatch(authRolePermissions);
        return count > 0;
    }
}
